"""
author: yzh
date: 2021/1/20
"""
import requests
import re
import execjs
from apps.DjangoWeb.spider.previousQuery.getOldJsessionID import getexe
from apps.DjangoWeb.spider.previousQuery.getKey import getkeyList

r_jwxt_login_url = 'https://authserver-443.webvpn.ecut.edu.cn/authserver/login?service=https%3A%2F%2Fjwxt-18801.webvpn.ecut.edu.cn%3A443%2Fcaslogin.jsp'
iPlanetDirectoryPro = ["",""]
getltList = ["","","","",""]

def jwxtlogin(username, password):

    getexe(username,password)

    r_jwxt_login_headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19',
        "Pragma": "no-cache",
        "Accept": "application/json, text/plain, */*",
        "Cookie": getkeyList[2]
    }
    r_jwxt = requests.get(r_jwxt_login_url, headers=r_jwxt_login_headers)

    getltList[0] = re.findall(r'name="lt" value="(.*?)"', r_jwxt.text)[0]
    getltList[1] = re.findall(r'name="execution" value="(.*?)"', r_jwxt.text)[0]
    getltList[2] = re.findall(r'pwdDefaultEncryptSalt = "(.*?)"', r_jwxt.text)[0]
    getltList[3] = 'route=' + re.findall(r'route=(.*?),', r_jwxt.headers['set-cookie'])[0] + ';'
    getltList[4] = 'JSESSIONID=' + re.findall(r'JSESSIONID=(.*?);', r_jwxt.headers['set-cookie'])[0] + ';'

    with open('apps/DjangoWeb/spider/tools/encrypt.wisedu.js', encoding='utf-8') as f:
        code = f.read()
        js_compile = execjs.compile(code)
        pwd1 = js_compile.call('encryptAES', password, getltList[2])

    r_jwxt_login_data = {
        'username': username,
        'password': pwd1,  # 需加密
        'lt': getltList[0],
        'dllt': 'userNamePasswordLogin',
        'execution': getltList[1],
        '_eventId': 'submit',
        'rmShown': 1
    }

    r_jwxt_login_headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19',
        "Pragma": "no-cache",
        "Accept": "application/json, text/plain, */*",
        "Cookie": getltList[3] + getkeyList[1] + getkeyList[0] + getltList[4]
    }
    r_jwxt_login = requests.post(r_jwxt_login_url, headers=r_jwxt_login_headers, data=r_jwxt_login_data, allow_redirects=False)
    # 第五次post登录教务系统
    iPlanetDirectoryPro[0] = 'iPlanetDirectoryPro='+re.findall(r'iPlanetDirectoryPro=(.*?);', r_jwxt_login.headers['set-cookie'])[0]+'; '
    iPlanetDirectoryPro[1] = re.findall(r'<a href="(.*?)"', r_jwxt_login.text)[0]
    return iPlanetDirectoryPro